/*
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Read MAX30102 heart rate sensor origin data with hi3861 I2C
**/

#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "iot_watchdog.h"
#include "cmsis_os2.h"
#include "iot_errno.h"

#include "hi_io.h"
#include "hi_gpio.h"
#include "iot_gpio.h"
#include "hi_time.h"
#include "hi_i2c.h"
#include "max30102_hello.h"

#define LED_IO 9
#define LED_ON 0
#define LED_OFF 1
#define DELAY_TIME 300000
#define TASK_STACK_SIZE 4096

uint8_t IR_channel_data, RED_channel_data;

static void *heartrateTask(const char *arg)
{
    (void)arg;

    IoTGpioInit(MAX_SDA_IO0);
    IoTGpioInit(MAX_SCL_IO1);
    hi_io_set_func(MAX_SDA_IO0, HI_IO_FUNC_GPIO_0_I2C1_SDA);
    hi_io_set_func(MAX_SCL_IO1, HI_IO_FUNC_GPIO_1_I2C1_SCL);
    hi_i2c_init(MAX_I2C_IDX, MAX_I2C_BAUDRATE);
    IoTGpioInit(LED_IO);
    IoTGpioSetDir(LED_IO, IOT_GPIO_DIR_OUT);
    max_init();
    while (1) {
        max_Data(&RED_channel_data, &IR_channel_data);
        IoTGpioSetOutputVal(LED_IO, LED_ON);
        usleep(DELAY_TIME);
        IoTGpioSetOutputVal(LED_IO, LED_OFF);
        usleep(DELAY_TIME);
        printf("RED_channel_data= %d \n", RED_channel_data);
        printf("IR_channel_data= %d \n", IR_channel_data);
    }
    return NULL;
}

static void HeartrateDemo(void)
{
    osThreadAttr_t attr;

    IoTWatchDogDisable();

    attr.name = "heartrateTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = osPriorityNormal;

    if (osThreadNew(heartrateTask, NULL, &attr) == NULL) {
        printf("[HeartrateDemo] Falied to create heartrateTask!\n");
    }
    printf("\r\n[HeartrateDemo] Succ to create heartrateTask!\n");
}
SYS_RUN(HeartrateDemo);